import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';

import {UserService} from '../../service/user.service';
import {Md5} from 'ts-md5';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  msg = null;
  // eui-datagrid（数据表格）
  itemForForm: FormGroup; // 表单对象
  formBtnDisabled = false; // 默认激活表单提交,true禁用表单提交
  formValidSuccess = true; // 默认成功样式
  placeholder = {
    email: {'title': '邮箱', 'prompt': 'you@example.com'},
    password: {'title': '密码', 'prompt': '字母开头,长度在6~10之间,只能包含字母、数字和下划线'},
  };

  /**
   * 构造函数
   */
  constructor(
    private router: Router,
    private userService: UserService,
    private formBuilder: FormBuilder) {
    this.createItemForForm(); // 创建表单对象
  }

  /**
   * 构造函数
   */
  ngOnInit() {
  }

  /**
   * 创建表单对象
   */
  createItemForForm(): void {
    this.itemForForm = this.formBuilder.group({
      email: [null, [
        Validators.required,
        Validators.pattern('^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$')]],
      password: [null, [
        Validators.required,
        Validators.pattern('^[a-zA-Z]\\w{5,9}$')
      ]]
    });
  }

  /**
   * 提交登录表单
   * @param userForm
   */
  onSubmitForm(itemForForm): void {
    this.formBtnDisabled = true; // 禁用表单提交
    itemForForm.value.password = Md5.hashStr(itemForForm.value.password).toString(); // 对密码进行加密
    this.userService.login(itemForForm.value).subscribe((responseJson) => {
      if (responseJson.code === 0) {
        /*
          操作成功
         */
        sessionStorage.clear();
        sessionStorage.setItem('jwt', responseJson.data.jwt);
        sessionStorage.setItem('name', responseJson.data.name);
        sessionStorage.setItem('cover', responseJson.data.cover);
        setTimeout(() => {
          this.router.navigateByUrl('/admin');
        }, 500);
      } else {
        /*
          操作失败
         */
        this.formBtnDisabled = false; // 激活表单提交
        this.formValidSuccess = false; // 失败样式
        this.msg = responseJson.msg;
      }
    });
  }
}
